<?php

namespace App\Store\Controllers\Order;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Member\MemberBalanceChangelog;
use App\Store\Models\Order\OrderPointschangebalance;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Member\Member;


use App\Common\Services\CommonExcelExport;
use App\Store\Models\Basic\PaytypeList;
use App\Store\Models\Member\MemberPointsChangelog;
use App\Store\Models\Member\SiteMemberLv;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\Excel\DownloadTemp;
use Illuminate\Support\Facades\DB;

use App\Store\Validate\Order\OrderPointschangebalance as ValidateOrderOrderPointschangebalance;

/**
 * 积分转预存开单
 */
class OrderPointschangebalanceController extends Controller
{
    /**
     * 开单
     */
    public function dopostorder(Request $request)
    {

        $req_data = $request->only([
            'mobile','money','points', 'order_at', 'remark',
            // 'issendpoints',
        ]);
        $Validate = new ValidateOrderOrderPointschangebalance();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '201', 'msg' => $Validate->getError()]);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $meminfo=Member::where(['cp_id'=>$cp_id,'mobile'=>$req_data['mobile'],'is_del'=>1])->first();
        if(!$meminfo){
            return response()->json(['code' => '001', 'msg' => '暂无此会员信息']);
        }
        if($meminfo->points_current<$req_data['points']){
            return response()->json(['code' => '001', 'msg' => '积分余额不足']);
        }




        $orderdata=[
            'money'=>$req_data['money'],
            'points'=>$req_data['points'],
            'shopping_account_id1'=>0,
            'shopping_account_id2'=>0,
            'classesset_id'=>0,
            'order_at' => isset($req_data['order_at']) ?strtotime($req_data['order_at']):time(),
            // 'issendpoints'=>$req_data['issendpoints'],
            'remark'=>isset($req_data['remark'])?$req_data['remark']:''
        ];
        // $orderdata['order_at']=strtotime($orderdata['order_at']);
        $current_store_id=0;
        $store_ids = $accountinfo['store_ids'];
        if (is_array($store_ids) || $store_ids == '' || $store_ids<=0) { //获取当前权限下的门店

            return response()->json(['code' => '001', 'msg' => '请使用店长或店员账号']);
        }else{
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $current_store_id = intval($store_ids);
            }
        }
        $orderdata['mem_id']=$meminfo->id;

        $orderdata['cp_id']=$cp_id;
        $orderdata['store_id']=$current_store_id;
        $orderdata['order_sn']=StoreCommon::createOrderSn();
        $orderdata['create_account_id'] = $accountinfo['id'];
        $orderdata['update_account_id'] = $accountinfo['id'];
        $orderdata['create_account_real_name'] = $accountinfo['real_name'];
        $orderdata['update_account_real_name'] = $accountinfo['real_name'];
        $orderdata['create_at'] = time();
        $orderdata['update_at'] = time();




        DB::beginTransaction();
        try {
            $id=OrderPointschangebalance::create($orderdata)->id;
            $info = OrderPointschangebalance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
            $balancelogdata=[
                'cp_id'=>$cp_id,
                'mem_id'=>$info->mem_id,
                'type'=>3,
                'store_id'=>$info->store_id,
                'change_val'=>$info->money,
                'change_before'=>$meminfo->pointstobalance,
                'change_after'=>$meminfo->pointstobalance+$info->money,
                'sales_account_id'=>$info->shopping_account_id1,
                'loginfo'=>json_encode(['title'=>'积分转预存']),
                'create_account_id' => $info->create_account_id,
                'update_account_id' => $info->update_account_id,
                'create_account_real_name' => $info->create_account_real_name,
                'update_account_real_name' => $info->update_account_real_name,
                'create_at' => time(),
                'update_at' => time(),
                'remark'=>$info->remark,
            ];

            $pointslogdata=[
                'cp_id'=>$cp_id,
                'mem_id'=>$info->mem_id,
                'type'=>5,
                'store_id'=>$info->store_id,
                'change_val'=>-$info->points,
                'change_before'=>$meminfo->points_current,
                'change_after'=>$meminfo->points_current-$info->points,
                'sales_account_id'=>$info->shopping_account_id1,
                'loginfo'=>json_encode(['title'=>'积分转预存']),
                'create_account_id' => $info->create_account_id,
                'update_account_id' => $info->update_account_id,
                'create_account_real_name' => $info->create_account_real_name,
                'update_account_real_name' => $info->update_account_real_name,
                'create_at' => time(),
                'update_at' => time(),
                'remark'=>$info->remark,
            ];

            OrderPointschangebalance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status'=>2,'audit_at'=>time()]);
            MemberBalanceChangelog::create($balancelogdata);
            MemberPointsChangelog::create($pointslogdata);


            Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
            'pointstobalance'=> DB::raw('pointstobalance + ' . ($info->money)),
           // 'pre_money'=>DB::raw('pre_money + ' . ($info->money)),
            'points_current'=> DB::raw('points_current - ' . $info->points),
            'points_used'=>DB::raw('points_used + ' . $info->points),
            ]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '操作失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '操作成功']);

    }

    /**
     * 挂单
     */
    public function dopostordermaker(Request $request)
    {

        $req_data = $request->only([
            'mobile','money','points', 'shopping_account_id1', 'shopping_account_id2', 'classesset_id', 'order_at', 'issendpoints','remark',
        ]);
        $Validate = new ValidateOrderOrderPointschangebalance();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $meminfo=Member::where(['cp_id'=>$cp_id,'mobile'=>$req_data['mobile'],'is_del'=>1])->first();
        if(!$meminfo){
            return response()->json(['code' => '001', 'msg' => '暂无此会员信息']);
        }
        if($meminfo->points_current<$req_data['points']){
            return response()->json(['code' => '001', 'msg' => '积分余额不足']);
        }




        $orderdata=[
            'money'=>$req_data['money'],
            'points'=>$req_data['points'],
            'shopping_account_id1'=>$req_data['shopping_account_id1'],
            'shopping_account_id2'=>$req_data['shopping_account_id2'],
            'classesset_id'=>$req_data['classesset_id'],
            'order_at'=>$req_data['order_at'],
            'issendpoints'=>$req_data['issendpoints'],
            'remark'=>isset($req_data['remark'])?$req_data['remark']:''
        ];
        $orderdata['order_at']=strtotime($orderdata['order_at']);
        $current_store_id=0;
        $store_ids = $accountinfo['store_ids'];
        if (is_array($store_ids) || $store_ids == '' || $store_ids<=0) { //获取当前权限下的门店

            return response()->json(['code' => '001', 'msg' => '请使用店长或店员账号']);
        }else{
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $current_store_id = intval($store_ids);
            }
        }
        $orderdata['mem_id']=$meminfo->id;

        $orderdata['cp_id']=$cp_id;
        $orderdata['store_id']=$current_store_id;
        $orderdata['order_sn']=date('YmdHis') .$cp_id.$current_store_id. rand(1000, 9999);
        $orderdata['create_account_id'] = $accountinfo['id'];
        $orderdata['update_account_id'] = $accountinfo['id'];
        $orderdata['create_account_real_name'] = $accountinfo['real_name'];
        $orderdata['update_account_real_name'] = $accountinfo['real_name'];
        $orderdata['create_at'] = time();
        $orderdata['update_at'] = time();
        // $orderdata['is_maker']=2;
        OrderPointschangebalance::create($orderdata);

        return response()->json(['code' => '000', 'msg' => '挂单成功']);

    }

    /**
     * 挂单支付
     */
    public function doordermakerpay(Request $request){
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderPointschangebalance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
        }
        // if($info->is_maker!=2){
        //     return response()->json(['code' => '001', 'msg' => '该订单不是挂单状态']);
        // }
        OrderPointschangebalance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['is_maker'=>1,'update_at'=>time()]);
        return response()->json(['code' => '000', 'msg' => '订单支付成功']);

    }

    /**
     * 订单列表
     */

    public function getorderlist(Request $request){
        $list = OrderPointschangebalance::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 订单详情
     */
    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderPointschangebalance::with(['memberinfo','shoppingaccountinfo1','shoppingaccountinfo2','storeinfo'])->where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 订单编辑
     */
    public function doorderedit(Request $request){
        $req_data = $request->only([
           'money','points', 'shopping_account_id1', 'shopping_account_id2', 'classesset_id', 'order_at', 'issendpoints','remark',
        ]);
        $id = $request->id ?? 0;
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = OrderPointschangebalance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        // if($info->is_maker!=1){
        //     return response()->json(['code' => '001', 'msg' => '该订单挂单中不可编辑']);
        // }
        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
        }


        $Validate = new ValidateOrderOrderPointschangebalance('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $meminfo=Member::where(['cp_id'=>$cp_id,'mobile'=>$info->mem_id,'is_del'=>1])->first();
        if(!$meminfo){
            return response()->json(['code' => '001', 'msg' => '暂无此会员信息']);
        }
        if($meminfo->points_current<$req_data['points']){
            return response()->json(['code' => '001', 'msg' => '积分余额不足']);
        }

        $orderdata=[
            'money'=>$req_data['money'],
            'points'=>$req_data['points'],
            'shopping_account_id1'=>$req_data['shopping_account_id1'],
            'shopping_account_id2'=>$req_data['shopping_account_id2'],
            'classesset_id'=>$req_data['classesset_id'],
            'order_at'=>$req_data['order_at'],
            'issendpoints'=>$req_data['issendpoints'],
            'remark'=>isset($req_data['remark'])?$req_data['remark']:''
        ];
        $orderdata['order_at']=strtotime($orderdata['order_at']);
        $orderdata['update_account_id'] = $accountinfo['id'];
        $orderdata['update_account_real_name'] = $accountinfo['real_name'];
        $orderdata['update_at'] = time();
        OrderPointschangebalance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update($orderdata);

        return response()->json(['code' => '000', 'msg' => '订单编辑成功']);
    }

    /**
     * 审核通过
     */
    public function doorderauditsuccess(Request $request){
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderPointschangebalance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
        }
        // if($info->is_maker!=1){
        //     return response()->json(['code' => '001', 'msg' => '该订单挂单中不可审核']);
        // }
        //用户增加余额

        $meminfo=Member::where(['cp_id'=>$cp_id,'id'=>$info->mem_id,'is_del'=>1])->first();
        if(!$meminfo){
            return response()->json(['code' => '001', 'msg' => '暂无此会员信息']);
        }
        if($meminfo->points_current<$info->points){
            return response()->json(['code' => '001', 'msg' => '积分余额不足']);
        }


        $balancelogdata=[
            'cp_id'=>$cp_id,
            'mem_id'=>$info->mem_id,
            'type'=>3,
            'store_id'=>$info->store_id,
            'change_val'=>$info->money,
            'change_before'=>$meminfo->pointstobalance,
            'change_after'=>$meminfo->pointstobalance+$info->money,
            'sales_account_id'=>$info->shopping_account_id1,
            'loginfo'=>json_encode(['title'=>'积分转预存']),
            'create_account_id' => $info->create_account_id,
            'update_account_id' => $info->update_account_id,
            'create_account_real_name' => $info->create_account_real_name,
            'update_account_real_name' => $info->update_account_real_name,
            'create_at' => time(),
            'update_at' => time(),
            'remark'=>$info->remark,
        ];

        $pointslogdata=[
            'cp_id'=>$cp_id,
            'mem_id'=>$info->mem_id,
            'type'=>5,
            'store_id'=>$info->store_id,
            'change_val'=>-$info->points,
            'change_before'=>$meminfo->points_current,
            'change_after'=>$meminfo->points_current-$info->points,
            'sales_account_id'=>$info->shopping_account_id1,
            'loginfo'=>json_encode(['title'=>'积分转预存']),
            'create_account_id' => $info->create_account_id,
            'update_account_id' => $info->update_account_id,
            'create_account_real_name' => $info->create_account_real_name,
            'update_account_real_name' => $info->update_account_real_name,
            'create_at' => time(),
            'update_at' => time(),
            'remark'=>$info->remark,
        ];




        DB::beginTransaction();
        try {

            OrderPointschangebalance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status'=>2,'audit_at'=>time()]);
            MemberBalanceChangelog::create($balancelogdata);
            MemberPointsChangelog::create($pointslogdata);
            Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
            'pointstobalance'=> DB::raw('pointstobalance + ' . ($info->money)),
            'points_current'=> DB::raw('points_current - ' . $info->points),
            'points_used'=>DB::raw('points_used + ' . $info->points),
            ]);


            //计算绩效？

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '订单审核成功']);
    }

    /**
     * 审核取消
     */
    public function doorderauditcancel(Request $request){
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderPointschangebalance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
        }

        // if($info->is_maker!=1){
        //     return response()->json(['code' => '001', 'msg' => '该订单挂单中不可审核']);
        // }
        OrderPointschangebalance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status'=>3,'audit_at'=>time()]);
        return response()->json(['code' => '000', 'msg' => '订单取消成功']);

    }
}
